package com.baizhi.cmfz.controller;

import com.baizhi.cmfz.entity.Article;
import com.baizhi.cmfz.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@RequestMapping("/article")
@Controller
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @RequestMapping("/showPageArticle")
    @ResponseBody
    public Map showPageArticle(int page, int limit ){
        return articleService.showPageArticle(page,limit);
    }

    @RequestMapping("/insertArticle")
    @ResponseBody
    public  Map insertArticle(Article article, MultipartFile file, HttpServletRequest request) throws IOException {
        //设置上传路径
        String realPath=request.getServletContext().getRealPath("/upload");
        //新文件重命名
        String newFile=new Date().getTime()+"_"+file.getOriginalFilename();
        file.transferTo(new File(realPath+"/"+newFile));
        article.setImage("/upload/"+newFile);
        return articleService.insertArticle(article);
    }

    @RequestMapping("/deleteArticle")
    @ResponseBody
    public Map deleteArticle(int id){
        return articleService.deleteArticle(id);
    }

    @RequestMapping("/showOne")
    @ResponseBody
    public Article showOne(int id){
        return  articleService.showOne(id);
    }

    @RequestMapping("/updateArticle")
    @ResponseBody
    public  Map updateArticle(Article article){
        return articleService.updateArticle(article);
    }
}
